# from django.forms import forms, models
import hashlib
from io import BytesIO

from django import forms
from django.core.validators import RegexValidator
from django.http import HttpResponse
from django.shortcuts import render, redirect

from web import models
from web.utils.code import check_code

'''登陆注册退出 '''
class LoginForm(forms.Form):
    '''登录'''
    username = forms.CharField(
        label="用户名",
        widget=forms.TextInput
    )
    password = forms.CharField(
        label="密码",
        widget=forms.PasswordInput
    )
    code = forms.CharField(
        label="验证码",
        widget=forms.TextInput,
        required=True
    )
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 循环找到所有的插件，添加了class="form-control"
        for name, field in self.fields.items():
            # if name == "password":
            #     continue
            field.widget.attrs = {"class": "form-control", "placeholder": field.label, "required":""}


def user_login(request):
    """ 登录 """
    if request.method == "GET":
        form = LoginForm()
        return render(request, 'login.html', {'form': form})

    form = LoginForm(data=request.POST)
    if form.is_valid():
        # 验证成功，获取到的用户名和密码
        # {'username': 'wupeiqi', 'password': '123',"code":123}
        # {'username': 'wupeiqi', 'password': '5e5c3bad7eb35cba3638e145c830c35f',"code":xxx}

        # 验证码的校验
        user_input_code = form.cleaned_data.pop('code')
        code = request.session.get('image_code', "")
        if code.upper() != user_input_code.upper():
            form.add_error("code", "验证码错误")
            return render(request, 'login.html', {'form': form})

        # 去数据库校验用户名和密码是否正确，获取用户对象、None
        # admin_object = models.Admin.objects.filter(username=xxx, password=xxx).first()
        admin_object = models.User.objects.filter(username=form.cleaned_data["username"]).first()
        # 将输入的密码加密成md5
        salt = "xueguanchao"
        Encry = hashlib.md5(salt.encode("utf-8"))
        password = form.cleaned_data["password"]
        Encry.update(password.encode("utf-8"))
        md5_pwd = Encry.hexdigest()
        if admin_object.username != form.cleaned_data["username"] or md5_pwd != admin_object.password:
            form.add_error("password", "用户名或密码错误")
            # form.add_error("username", "用户名或密码错误")
            return render(request, 'login.html', {'form': form})

        # 用户名和密码正确
        # 网站生成随机字符串; 写到用户浏览器的cookie中；在写入到session中；
        request.session["info"] = {'id': admin_object.id, 'username': admin_object.username}
        # session可以保存7天
        request.session.set_expiry(60 * 60 * 24 * 7)

        return redirect("/index/")

    return render(request, 'login.html', {'form': form})



class UserModelForm(forms.ModelForm):
    phone = forms.CharField(
        label="手机号",
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误'), ],
    )
    email = forms.CharField(
        label="邮箱",
        validators=[RegexValidator(r'^[0-9a-za-z_]{0,19}@[0-9a-za-z]{1,13}\.[com,cn,net]{1,3}$', '邮箱格式错误'), ],
    )

    class Meta:
        model = models.User
        fields = ["username", "password", "email", "phone", "gender"]


    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 循环找到所有的插件，添加了class="form-control"
        for name, field in self.fields.items():
            # if name == "email":
            #     continue
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}

def user_register(request):
    """ 添加用户（ModelForm版本）"""
    if request.method == "GET":
        form = UserModelForm()
        return render(request, 'register.html', {"form": form})

    # 用户POST提交数据，数据校验。
    form = UserModelForm(data=request.POST)
    if form.is_valid():
        # 如果数据合法，保存到数据库
        # 密码加盐
        salt = "xueguanchao"
        Encry = hashlib.md5(salt.encode("utf-8"))
        password = form.cleaned_data["password"]
        Encry.update(password.encode())
        md5_pwd = Encry.hexdigest()
        models.User.objects.create(username=form.cleaned_data["username"], password=md5_pwd,
                                   email=form.cleaned_data["email"], phone=form.cleaned_data["phone"],
                                   gender=form.cleaned_data["gender"])
        return redirect('/user/login/')

    # 校验失败（在页面上显示错误信息）
    return render(request, 'register.html', {"form": form})

def user_logout(request):
    request.session.clear()
    return redirect("/user/login/")

def image_code(request):
    """ 生成图片验证码 """
    # 调用pillow函数，生成图片
    img, code_string = check_code()
    # 写入到自己的session中（以便于后续获取验证码再进行校验）
    request.session['image_code'] = code_string
    # 给Session设置60s超时
    request.session.set_expiry(60)

    stream = BytesIO()
    img.save(stream, 'png')
    return HttpResponse(stream.getvalue())